package com.traffic.managent.model.system;

import java.util.List;

import com.traffic.managent.annotation.ModelBind;
import com.traffic.managent.base.SessionUser;
import com.traffic.managent.jedis.RedisKit;
import com.traffic.managent.model.customer.Customer;
import com.traffic.managent.plugin.ParamInitThread;
import com.traffic.managent.util.StringUtils;

@ModelBind(table = "cx_user", key = "ids")
public class User extends SessionUser<User> {

	private static final long serialVersionUID = 1L;
	public static final User dao = new User();

	public String getUserid() {
		return getStr("ids");
	}

	public String getUserName() {
		if (StringUtils.isNotEmpty(getStr("username"))) {
			return getStr("username");
		}
		return getStr("username");
	}

	/**
	 * 根据客户id查询
	 * 
	 */
	public List<User> findByCustomerId(String customerId) {
		List<User> list = User.dao.find("select * from cx_user where status = '1' and customerId = ?", customerId);
		return list;
	}

	/**
	 * 关联查询，获取用户详细信息
	 * 
	 * @return
	 */
	public UserInfo getUserInfo() {
		String userinfoIds = get("userinfoids");
		if (null != userinfoIds && !userinfoIds.isEmpty()) {
			return UserInfo.dao.findById(userinfoIds);
		}
		return null;
	}

	/**
	 * 添加或者更新缓存
	 */
	public void cacheAdd(String ids) {
		User user = User.dao.findById(ids);
		if (user != null) {
			RedisKit.put(ParamInitThread.cacheStart_user + ids, user);
			RedisKit.put(ParamInitThread.cacheStart_user + user.getStr("username"), user);

			// 缓存用户appkey与代理商privateKey 关系
			String cid = user.getStr("customerId");

			Customer c = RedisKit.get(ParamInitThread.cacheStart_customer + cid);
			if (c != null) {
				// 将私钥跟appkey映射放入缓存中
				RedisKit.put(ParamInitThread.cacheStart_appkey + user.getStr("username"), c.getStr("privateKey"));
				// 将bindIps跟appkey映射放入缓存中
				RedisKit.put(ParamInitThread.cacheStart_bindips + user.getStr("username"), c.getStr("bindIps"));
			}
		}
	}

	/**
	 * 删除缓存
	 */
	public void cacheRemove(String ids) {
		User user = User.dao.findById(ids);
		RedisKit.remove(ParamInitThread.cacheStart_user + ids);
		RedisKit.remove(ParamInitThread.cacheStart_user + user.getStr("username"));
	}

}
